<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑错题' : '新增错题'"
    width="600px"
    @close="handleClose"
  >
    <div class="mistake-editor">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <!-- 科目选择 -->
        <el-form-item label="科目" prop="subjectId">
          <el-select
            v-model="formData.subjectId"
            placeholder="请选择科目"
            style="width: 100%"
          >
            <el-option
              v-for="subject in safeSubjects"
              :key="subject.id"
              :label="subject.name"
              :value="subject.id"
            />
          </el-select>
        </el-form-item>

        <!-- 标题 -->
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入标题"
            maxlength="100"
            show-word-limit
            ref="titleInput"
          />
        </el-form-item>

        <!-- 内容 -->
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="6"
            placeholder="请输入错题内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item label="图片">
          <div class="image-upload-section">
            <!-- 有图片时显示 -->
            <div v-if="formData.imageUrl" class="preview-section">
              <img :src="formData.imageUrl" alt="错题图片" class="preview-image" />
              <div class="preview-actions">
                <el-button size="small" @click="triggerUpload">更换</el-button>
                <el-button size="small" type="danger" @click="removeImage">删除</el-button>
              </div>
            </div>

            <!-- 没有图片时显示 -->
            <div v-else class="upload-section">
              <el-upload
                ref="uploadRef"
                :auto-upload="false"
                :show-file-list="false"
                accept="image/jpeg,image/jpg,image/png,image/gif"
                :on-change="handleImageChange"
                :before-upload="beforeImageUpload"
              >
                <el-button type="primary">选择图片</el-button>
              </el-upload>
              <div class="upload-hint">支持JPG、PNG、GIF格式，不超过5MB</div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 对话框底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleSave"
          :loading="loading"
        >
          {{ isEdit ? '保存' : '创建' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useMistakeStore } from '@/store/mistake'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  question: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const mistakeStore = useMistakeStore()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.question)

const formRef = ref()
const uploadRef = ref()
const titleInput = ref()
const loading = ref(false)
const currentFile = ref(null)

const formData = ref({
  subjectId: '',
  title: '',
  content: '',
  imageUrl: ''
})

// 安全的科目数据
const safeSubjects = computed(() => {
  return mistakeStore.subjects || []
})

const rules = {
  subjectId: [
    { required: true, message: '请选择科目', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度为1-100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入错题内容', trigger: 'blur' }
  ]
}

// 初始化表单数据
const initFormData = () => {
  if (props.question) {
    formData.value = {
      subjectId: props.question.subjectId,
      title: props.question.title || '',
      content: props.question.content,
      imageUrl: props.question.imageUrl || '',
      isTemporaryImage: false
    }
  } else {
    formData.value = {
      subjectId: '',
      title: '',
      content: '',
      imageUrl: '',
      isTemporaryImage: false
    }
  }
  currentFile.value = null
}

// 上传前检查
const beforeImageUpload = (file) => {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
  const isAllowedType = allowedTypes.includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 10

  if (!isAllowedType) {
    ElMessage.error('只支持JPG、PNG、GIF格式的图片')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过10MB')
    return false
  }

  return true
}

// 图片选择变化
const handleImageChange = (file) => {
  const isAllowedType = beforeImageUpload(file.raw)
  if (!isAllowedType) {
    return false
  }

  currentFile.value = file.raw

  // 创建本地预览URL（仅用于预览，不上传到数据库）
  const reader = new FileReader()
  reader.onload = (e) => {
    // 临时保存预览URL，标记这是临时文件
    formData.value.imageUrl = e.target.result
    formData.value.isTemporaryImage = true
  }
  reader.readAsDataURL(file.raw)
}

// 触发上传（用于更换图片）
const triggerUpload = () => {
  uploadRef.value?.$el.querySelector('input').click()
}

// 移除图片
const removeImage = () => {
  formData.value.imageUrl = ''
  currentFile.value = null
  uploadRef.value?.clearFiles()
}

// 保存错题
const handleSave = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true

    // 如果有新选择的图片，先上传到服务器
    if (currentFile.value) {
      try {
        const uploadResponse = await mistakeStore.uploadImage(currentFile.value, formData.value.subjectId)
        formData.value.imageUrl = uploadResponse.data
        formData.value.isTemporaryImage = false
      } catch (uploadError) {
        console.error('图片上传失败:', uploadError)
        ElMessage.error('图片上传失败，请重试')
        return
      }
    }
    // 如果是编辑状态且有临时图片，但选择了不同的科目，需要重新上传
    else if (formData.value.isTemporaryImage && formData.value.subjectId) {
      ElMessage.error('请重新上传图片')
      return
    }

    await mistakeStore.createQuestion(formData.value)

    ElMessage.success(isEdit.value ? '保存成功' : '创建成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('保存错题失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  formData.value = {
    subjectId: '',
    title: '',
    content: '',
    imageUrl: '',
    isTemporaryImage: false
  }
  currentFile.value = null
  uploadRef.value?.clearFiles()
  formRef.value?.resetFields()
  emit('update:modelValue', false)
}

// 监听对话框显示状态
watch(visible, async (newVal) => {
  if (newVal) {
    await mistakeStore.fetchSubjects()
    initFormData()
    // 延迟聚焦，确保DOM已渲染
    setTimeout(() => {
      titleInput.value?.focus()
    }, 100)
  }
})

onMounted(async () => {
  await mistakeStore.fetchSubjects()
})
</script>

<style scoped>
.mistake-editor {
  padding: 20px 0;
}

.image-upload-section {
  width: 100%;
}

.preview-section {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px;
}

.preview-image {
  width: 100%;
  max-height: 200px;
  object-fit: contain;
  border-radius: 4px;
}

.preview-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.upload-section {
  text-align: center;
  padding: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}

.upload-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>